const cryptoUtils = require('../utils/crypto_utils');
const userTable = require('../models/user');
const config = require('../config')

const WHITE_LIST = [
    '/confirm',
    '/reset_pwd',
    '/403',
    '/404',
    '/500',
]

let authorize = async function (ctx, next) {

    let go = ctx.query.go ? '?go=' + ctx.query.go : '';

    let cookie = ctx.request.headers.cookie;

    let cookies = {};

    if (WHITE_LIST.some(item => ctx.path.indexOf(item) === 0)) {
        return next();
    }

    // 有cookie并取出对应的值
    if (cookie) {

        let list = cookie.split(';');

        for (let i = 0; i < list.length; i++) {

            let pair = list[i].split('=');

            cookies[pair[0].trim()] = pair[1];

        }
    }

    ctx.request.cookies = cookies
    ctx.request.cookies.userId = null;

    if (cookies['token']) {

        let tokenStr = cryptoUtils.decrypt(cookies['token']);

        let result = await userTable.getUser(tokenStr.split('&')[0]);
        console.log(result)
        console.log(ctx.path)
        if (!result || result.length === 0) {

            if (!config.ENV || config.ENV === 'ONLINE') {

                if (ctx.path === '/sign') {
                    return next();
                }

                return ctx.redirect('/sign' + go);

            } else if (config.ENV === 'K8S') {

                if (ctx.path === '/home') {
                    return next();
                }

                return ctx.redirect('/home' + go);
            }

        }


        if (ctx.path === '/sign') {
            return ctx.redirect('/');
        }

        ctx.request.cookies.userId = result[0].id;

        await next();

        return;

    } else {

        if (ctx.path === '/sign') {
            return next();
        }
        if(!config.ENV || config.ENV === 'ONLINE'){
            await ctx.redirect('/sign' + go);
        }else if(config.ENV === 'K8S'){
            await ctx.redirect('/home' + go);
        }
        

    }
}

module.exports = authorize;
